package com.media.publish;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.viewpager.widget.ViewPager;

import com.baselibrary.activity.BaseActivity;
import com.baselibrary.bean.ReleaseTopicBean;
import com.baselibrary.manager.RecycleViewManager;
import com.baselibrary.manager.SensorsDataManager;
import com.baselibrary.utils.HKToastUtils;
import com.baselibrary.utils.KeyBoardUtils;
import com.baselibrary.utils.SpUtils;
import com.baselibrary.utils.SpringViewNewFooter;
import com.baselibrary.utils.SpringViewNewHeader;
import com.liaoinstan.springview.widget.SpringView;
import com.media.R;
import com.media.databinding.ActivitySearchTopicBinding;
import com.okhttp.SendRequest;
import com.okhttp.callbacks.GenericsCallback;
import com.okhttp.callbacks.IGenericsSerializator;
import com.okhttp.sample_okhttp.JsonGenericsSerializator;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import com.media.publish.adapter.DynamicSearchTopicAdapter;
import com.media.publish.adapter.DynamicSearchTopicTabAdapter;
import com.media.publish.adapter.TopicMenuAdapter;
import com.media.publish.bean.DoyTypeData;

/**
 * @author 关忆北、
 * @description 发布动态-选择话题
 * @time 2022/4/21 9:47 上午
 */
public class SearchTopicActivity extends BaseActivity implements TextWatcher, View.OnClickListener {
    private ActivitySearchTopicBinding mBinding;
    private DynamicSearchTopicAdapter mTopicListAdapter;
    private boolean isRefresh = false;
    private int mPageCount = 0;
    private final List<ReleaseTopicBean.DataBean> mAllList = new ArrayList<>();
    private final List<ReleaseTopicBean.DataBean> mPageList = new ArrayList<>();
    private String mLastFriendsName;
    private DynamicSearchTopicTabAdapter mDynamicSearchTopicTabAdapter;
    private TopicMenuAdapter mTopicMenuAdapter;
    private List<DoyTypeData.DataBean> mTopicMenu;
    private int mTopicMenuPos = -1;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_search_topic;
    }

    @Override
    protected void init() {
        setStatusBarHeight(R.color.white);
        mBinding = getDataBinding();
        initData();
        initListener();
        SensorsDataManager.Companion.getInstance().publishTrendsTalkView();
    }

    private void initData() {
        mBinding.includeTitle.tvDynamicSearchTop.setText("不添加话题");
        mTopicListAdapter = new DynamicSearchTopicAdapter();
        mDynamicSearchTopicTabAdapter = new DynamicSearchTopicTabAdapter(getSupportFragmentManager());
        mTopicMenuAdapter = new TopicMenuAdapter();
        mBinding.rvSearchtopicList.setAdapter(mTopicListAdapter);
        mTopicListAdapter.setOnItemClickListener((adapter, view, position) -> {
            ReleaseTopicBean.DataBean topicBean = (ReleaseTopicBean.DataBean) adapter.getData().get(position);
            if (topicBean != null) {
                KeyBoardUtils.hideShowKeyboard(SearchTopicActivity.this);
                Intent intent = new Intent();
                intent.putExtra("topicBean", topicBean);
                setResult(200, intent);
                finish();
            }
        });

        mBinding.rvSearchTopicTab.setAdapter(mTopicMenuAdapter);
        mBinding.vpSearchTopicList.setAdapter(mDynamicSearchTopicTabAdapter);
        getTopicList();

    }

    private void initListener() {
        mBinding.edtSearchtopic.addTextChangedListener(this);
        mBinding.ivSearchtopicSearch.setOnClickListener(this);
        mBinding.llSearchtopicEmpty.setOnClickListener(this);
        mBinding.ivBack.setOnClickListener(this);

        mBinding.svSearchtopic.setHeader(new SpringViewNewHeader(getApplicationContext()));
        mBinding.svSearchtopic.setFooter(new SpringViewNewFooter(getApplicationContext()));
        mBinding.svSearchtopic.setType(SpringView.Type.FOLLOW);

        mBinding.edtSearchtopic.setOnEditorActionListener((textView, i, keyEvent) -> {
            //隐藏软键盘
            @SuppressLint("WrongConstant") InputMethodManager imm = (InputMethodManager) getSystemService("input_method");
            imm.toggleSoftInput(0, 2);
            if (TextUtils.isEmpty(mBinding.edtSearchtopic.getText().toString())) {
                HKToastUtils.showToast("请输入搜索关键字");
                getTopicsList("", true);
            } else {
                getTopicsList(mBinding.edtSearchtopic.getText().toString(), false);
            }
            return true;
        });

        mBinding.svSearchtopic.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                getTopicsList(mLastFriendsName, (TextUtils.isEmpty(mLastFriendsName)));
            }

            @Override
            public void onLoadmore() {
                isRefresh = false;
                setPageList();
            }
        });

        mTopicMenuAdapter.setOnItemClickListener((adapter, view, position) -> {
            mTopicMenuPos = position;
            for (int i = 0; i < mTopicMenu.size(); i++) {
                mTopicMenu.get(i).setSelect(i == position);
            }
            mTopicMenuAdapter.setNewData(mTopicMenu);
            mBinding.vpSearchTopicList.setCurrentItem(position);
        });
        mBinding.vpSearchTopicList.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (mTopicMenuPos == position) {
                    mTopicMenuPos = -1;
                    //执行setCurrentItem这里也会回掉，所以 下标一样的情况下不做操作
                    return;
                }
                for (int i = 0; i < mTopicMenu.size(); i++) {
                    mTopicMenu.get(i).setSelect(i == position);
                }
                mTopicMenuAdapter.setNewData(mTopicMenu);
                RecycleViewManager.smoothMoveToPosition1(mBinding.rvSearchTopicTab, position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mBinding.includeTitle.llDoNotAdd.setOnClickListener(view -> {
            //不添加
            Intent intent = new Intent();
            setResult(200, intent);
            finish();
        });
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (editable.toString().length() <= 0) {
            mBinding.llSearchtopicEmpty.setVisibility(View.GONE);
            mBinding.svSearchtopic.setVisibility(View.GONE);
            mBinding.tvSearchtopicEmpty.setVisibility(View.GONE);
            getTopicsList(editable.toString(), true);
        } else {
            mBinding.llSearchtopicEmpty.setVisibility(View.VISIBLE);
            getTopicsList(editable.toString(), false);
        }
    }

    public void getTopicsList(String friendsName, boolean isDef) {
        mBinding.llTopicMenu.setVisibility(View.GONE);
        mBinding.include.setVisibility(View.GONE);
        mLastFriendsName = friendsName;
        mPageList.clear();
        if (isDef) {
            mBinding.llTopicMenu.setVisibility(View.VISIBLE);
            mBinding.include.setVisibility(View.VISIBLE);
            mBinding.svSearchtopic.setVisibility(View.GONE);
        } else {
            SendRequest.releaseSearchTopics(SpUtils.getInstance().getLoadUserBean().getData().getToken(), friendsName, new SearchTopic(new JsonGenericsSerializator()));
        }
    }
    //话题分类
    public void getTopicList() {

        SendRequest.tag_getList(SpUtils.getInstance().getUserToken(), new GenericsCallback<DoyTypeData>(new JsonGenericsSerializator()) {

            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(DoyTypeData response, int id) {
                if (response != null) {
                    mTopicMenu = response.getData();
                    mDynamicSearchTopicTabAdapter.setData(mTopicMenu);
                    mTopicMenu.get(0).setSelect(true);//第一个默认选中
                    mTopicMenuAdapter.setNewData(mTopicMenu);
                }

            }
        });
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_searchtopic_search) {
            if (TextUtils.isEmpty(mBinding.edtSearchtopic.getText().toString())) {
                getTopicsList("", true);
                return;
            }
            getTopicsList(mBinding.edtSearchtopic.getText().toString(), false);
        } else if (id == R.id.ll_searchtopic_empty) {
            mBinding.llSearchtopicEmpty.setVisibility(View.GONE);
            mBinding.tvSearchtopicEmpty.setVisibility(View.GONE);
            mBinding.edtSearchtopic.setText("");
            getTopicsList("", true);
        } else if (id == R.id.iv_back) {
            finish();
        }
    }


    public class SearchTopic extends GenericsCallback<ReleaseTopicBean> {


        public SearchTopic(IGenericsSerializator serializator) {
            super(serializator);
        }

        @Override
        public void onError(Call call, Exception e, int id) {
            mBinding.svSearchtopic.setVisibility(View.GONE);
            mBinding.tvSearchtopicEmpty.setVisibility(View.VISIBLE);
            mPageCount = 0;
            mBinding.svSearchtopic.onFinishFreshAndLoad();
        }

        @Override
        public void onResponse(ReleaseTopicBean response, int id) {
            mBinding.svSearchtopic.onFinishFreshAndLoad();

            if (TextUtils.isEmpty(mBinding.edtSearchtopic.getText().toString())) {
                //因为网络回执是异步的，所以需要先判断内容框是否还是属于搜索状态
                mBinding.llTopicMenu.setVisibility(View.VISIBLE);
                mBinding.include.setVisibility(View.VISIBLE);
                mBinding.svSearchtopic.setVisibility(View.GONE);
                return;
            }

            if (response.isSuccess()) {
                if (response.getData() != null && response.getData().size() > 0) {

                    mBinding.tvSearchtopicEmpty.setVisibility(View.GONE);
                    mBinding.svSearchtopic.setVisibility(View.VISIBLE);

                    mAllList.clear();
                    mAllList.addAll(response.getData());
                    setPageList();
                } else {
                    mBinding.svSearchtopic.setVisibility(View.GONE);
                    mBinding.tvSearchtopicEmpty.setVisibility(View.VISIBLE);
                    mPageCount = 0;
                }
            }
        }
    }


    private void setPageList() {
        if (isRefresh) {//这里的清空貌似没啥用
            mPageList.clear();
            mPageCount = 0;
        }
        int mPageSize = mPageList.size();
        int mAllSize = mAllList.size();
        if (mPageSize >= mAllSize) {
            mBinding.svSearchtopic.onFinishFreshAndLoad();
//            ToastUtil.toastShortMessage("已经全部加载完成");
            return;
        }
        for (int i = mPageSize; i < mAllSize; i++) {
            if (mPageCount == 20) {
                mBinding.svSearchtopic.onFinishFreshAndLoad();
                break;
            }
            mPageCount += 1;
            mPageList.add(mAllList.get(i));
            if (mPageList.size() == mAllSize) {
                mBinding.svSearchtopic.onFinishFreshAndLoad();
//                ToastUtils.showShort(this,"已经全部加载完成");
                break;
            }
        }
        mTopicListAdapter.setNewData(mPageList);
        mTopicListAdapter.notifyDataSetChanged();
        mPageCount = 0;

    }
}
